/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session.TX;

import entity.Advertisement;
import entity.AdvertisementStatistics;
import entity.Stakeholder;
import java.util.Date;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.*;
import javax.persistence.Query;

/**
 *
 * @author AdminNUS
 */
@Stateless
public class AdvertisementSB implements AdvertisementSBRemote {

    @PersistenceContext()
    EntityManager em;

    public boolean addAdvertisement(String tags,
            String filePath,
            String description,
            String link,
            boolean isSubscription,
            boolean isImpression,
            Double biddingPrice,
            boolean isActivated,
            Integer maxClicks,
            Integer maxImpression, String stakeholderName, Date startDate, Date endDate)
    {
	
		Query q = em.createQuery("SELECT c FROM Stakeholder c WHERE c.name = :paramName");
		q.setParameter("paramName", stakeholderName);
		List resultList = q.getResultList();
		if(resultList.isEmpty()) return false;
		 
		
        Stakeholder stakeholder = (Stakeholder) resultList.get(0);
        Advertisement ads = new Advertisement();
        AdvertisementStatistics adstats = new AdvertisementStatistics();
        List <AdvertisementStatistics> adstatsList = new ArrayList<AdvertisementStatistics>();
        
        if(stakeholder!=null)
        {
            ads.setTags(tags);
            ads.setFilePath(filePath);
            ads.setDescription(description);
            ads.setLink(link);
            ads.setIsSubscription(isSubscription);
            ads.setIsImpression(isImpression);
            ads.setBiddingPrice(biddingPrice);
            ads.setIsActivated(true);
            ads.setMaxClicks(maxClicks);
            ads.setMaxImpression(maxImpression);
            ads.setStakeholder(stakeholder);
            
            adstats.setStartDate(startDate);
            adstats.setEndDate(endDate);
            adstats.setNoOfClicks(0);
            adstats.setNoOfImpressions(0);
            em.persist(adstats);
            
            adstatsList.add(adstats);
            ads.setAdvertisementStatistics(adstatsList);
            em.persist(ads);
            
            return true;
        }
        
        
        return false;
    }
    
}
